package com.liangzhong.proxy.logic
{
	import com.adobe.serialization.json.JSON;
	import com.liangzhong.commandconst.logic.CMD_Logic;
	import com.liangzhong.commandconst.pub.CMD_Pub_Match;
	import com.liangzhong.commandconst.pub.CMD_Pub_Match_Result;
	import com.liangzhong.commandconst.pub.CMD_Public;
	import com.liangzhong.constants.HttpRequestConst;
	import com.liangzhong.constants.NotificationConstants;
	import com.liangzhong.errortip.ErrorTips;
	import com.liangzhong.events.AppEventDispatcher;
	import com.liangzhong.events.GuideEvent;
	import com.liangzhong.events.NotifierEvent;
	import com.liangzhong.global.CMD_Head;
	import com.liangzhong.model.AppData;
	import com.liangzhong.model.club.vo.BuffVo;
	import com.liangzhong.model.match.MatchServerDataParse;
	import com.liangzhong.model.match.vo.MatchEndAwardVo;
	import com.liangzhong.model.match.vo.MatchResultVo;
	import com.liangzhong.model.stadium.stadiumDataManager.FriendMatchInfoVo;
	import com.liangzhong.model.type.MatchType;
	import com.liangzhong.model.user.MoneyChange;
	import com.liangzhong.proxy.BaseProxy;
	import com.liangzhong.proxy.ProxyUtils;
	import com.socket.clientsocket.IClientSocket;
	
	import flash.events.Event;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import lz.controls.Alert;

	/**
	 *一般逻辑处理 
	 * @author lake
	 * 
	 */	
	public class LogicProxy extends BaseProxy
	{
		public static const ProxyName :String = "LogicProxy";

		public function LogicProxy(proxyName:String = ProxyName, data:Object=null)
		{
			super(proxyName, data);
		}
		/**
		 * 数据读取
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @param clientSocket
		 * @return 
		 */		
		override public function onSocketRead(mainCmdID:uint,
											  subCmdID:uint,
											  buffer:ByteArray, 
											  dataSize:int, 
											  clientSocket:IClientSocket):Boolean
		{
			switch(mainCmdID)
			{
				case CMD_Logic.MAIN://主
				{
					return onDeal(mainCmdID,subCmdID,buffer,dataSize);
				}
				case CMD_Public.MAIN://公用协议
				{
					return onDealPub(mainCmdID,subCmdID,buffer,dataSize);
				}
				case CMD_Pub_Match.MAIN://比赛公用
				{
					return onDealMatchPub(mainCmdID,subCmdID,buffer,dataSize);
				}
				case CMD_Pub_Match_Result.MAIN://比赛结果
				{
					return onDealMatchPubResult(mainCmdID,subCmdID,buffer,dataSize);
				}
			}
			return false;
		}
		/**
		 * 处理信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 */		
		private function onDealMatchPubResult(mainCmdID:uint,
										subCmdID:uint,
										buffer:ByteArray, 
										dataSize:int):Boolean
		{
			var retcode :int;
			switch(subCmdID)
			{
				case CMD_Pub_Match_Result.SUB_MATCH_RESULT://比赛结果
				{
					var matchResultVo :MatchResultVo = MatchServerDataParse.readMatchResult(buffer);
					AppData.getInstance().leagueMatchManager.updateResult(matchResultVo);
					
					
					switch(matchResultVo.ntype)
					{
						case MatchType.LADDYMATCH:
							AppData.getInstance().ladderDataManger.getMatchOnceResult(matchResultVo);
							this.sendNotification(NotificationConstants.LADDER_MATCH_END,matchResultVo);
							break;
						case MatchType.FRIENDMATCH:
							AppData.getInstance().friendManager.matchResult(matchResultVo);
							break;
					}
					return true;
				}
				case CMD_Logic.MATCH_END_AWARD://比赛奖励
				{
					var matchEndAwardVo :MatchEndAwardVo = MatchServerDataParse.readMatchAward(buffer);
					this.sendNotification(NotificationConstants.MATCH_SELECT_AWARD + matchEndAwardVo.matchId,matchEndAwardVo);
					return true;
				}
				case CMD_Logic.MATCH_END_GET_AWARD://手动抽奖
				{
					retcode = buffer.readInt();
					if(retcode == 0)
					{
						var awardIndex :int = buffer.readByte();
						var i :int = 0;
						var obj :Object;
						var pids :Array = [];
						for(;i < 4;i++)
						{
							obj = {};
							obj.id = buffer.readInt();
							obj.type = buffer.readByte();
							pids.push(obj);
						}
						AppEventDispatcher.getInstance().dispatchEvt(NotifierEvent.MATCH_USER_AWARD_RES,{pids:pids,ret:0});
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retcode) + "");
						AppEventDispatcher.getInstance().dispatchEvt(NotifierEvent.MATCH_USER_AWARD_RES,{pids:pids,ret:1});
					}
					return true;
				}
			}
			return false;
		}
		/**
		 * 处理信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 */		
		private function onDealMatchPub(mainCmdID:uint,
								subCmdID:uint,
								buffer:ByteArray, 
								dataSize:int):Boolean
		{
			var retcode :int;
			var matchId :uint;
			switch(subCmdID)
			{
				case CMD_Pub_Match.MATCH_DATA_RES://比赛数据返回
				{
					retcode = buffer.readInt();
					if(retcode == 0)
					{
						var opponentMatchInfo :FriendMatchInfoVo = new FriendMatchInfoVo();
						var selfMatchInfo :FriendMatchInfoVo = new FriendMatchInfoVo();
						opponentMatchInfo.analysisData(buffer);
						matchId = opponentMatchInfo.matchid;
						AppData.getInstance().stadiumDataManager.opponentMatchInfo[matchId] = opponentMatchInfo;
						selfMatchInfo.parseSelf(matchId);
						AppData.getInstance().stadiumDataManager.selfMatchInfo[matchId] = selfMatchInfo;
						this.sendNotification(NotificationConstants.MATCH_START_LOAD_RES,{matchId:matchId,type:opponentMatchInfo.matchType});
						//联赛减体力
						switch(opponentMatchInfo.matchType)
						{
							case MatchType.PRE_MATCH:
							case MatchType.BASE_MATCH:
							case MatchType.CHAMPION_MATCH:
							case MatchType.LEGEND_MATCH:
							{
								AppData.getInstance().playerCenterDataManager.reducePlayerPhysical();
								break;
							}
						}
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retcode) + "");
					}
					return true;
				}
			}
			return false;
		}
		/**
		 *处理 
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 */		
		private function onDealPub(mainCmdID:uint,
								   subCmdID:uint,
								   buffer:ByteArray, 
								   dataSize:int):Boolean
		{
			var retcode 	:int;
			var len			:int;
			var playerId	:int;
			var starId		:int;
			switch(subCmdID)
			{
				case CMD_Public.SUB_ADD_PLAYER://增加球员
				{
					retcode = buffer.readInt();
					if(retcode == 0)
					{
						playerId = buffer.readInt();
						starId = buffer.readInt();
						var number:int = buffer.readByte();
						var ability:int =buffer.readShort();
						var nextexp:int = buffer.readInt();
						this.sendNotification(NotificationConstants.ADD_PLAYER,{playerId:playerId,starId:starId,number:number,ability:ability,nextexp:nextexp});
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retcode) + "");
					}
					return true;
				}
				case CMD_Public.SUB_BUFF_CHANGE://buff变化
				{
					retcode = buffer.readInt();
					if(retcode == 0)
					{
						len = buffer.readShort();
						var buffVo :BuffVo;
						var buffPos :int ;//buff 位置 （1 --- 15）
						for(var i:int = 0;i<len;i++)
						{
							buffPos = buffer.readByte();
							buffVo = new BuffVo();
							buffVo.buffid 	= buffer.readUnsignedInt();
							buffVo.time 	= buffer.readUnsignedInt();
							buffVo.contime 	= buffer.readUnsignedInt();
							AppData.getInstance().clubDatamanager.changeBuff(buffVo,buffPos);
						}
						AppEventDispatcher.getInstance().dispatchEvent(new Event(NotifierEvent.BUFFER_CHANFE));
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retcode) + "");
					}
					return true;
				}
				case CMD_Public.SUB_CLUB_EXP_CHANGE://俱乐部经验改变
				{
					retcode = buffer.readInt();
					var clubLev 	:int = buffer.readShort();//俱乐部等级
					var clubexp		:int = buffer.readInt();//俱乐部经验
					var clubnextexp :int = buffer.readInt();//下级经验
					AppData.getInstance().clubDatamanager.clubInfo.setLevelExp({level :clubLev,exp:clubexp,nextexp:clubnextexp});
					return true;
				}
			}
			return false;
		}
		/**
		 * 处理信息
		 * @param mainCmdID
		 * @param subCmdID
		 * @param buffer
		 * @param dataSize
		 * @return 
		 */		
		private function onDeal(mainCmdID:uint,
								subCmdID:uint,
								buffer:ByteArray, 
								dataSize:int):Boolean
		{
			var retcode :int;
			var type	:int;
			switch(subCmdID)
			{
				case CMD_Logic.DROP_BUILDING_Time://去除冷却时间
				{
					retcode = buffer.readInt();
					if(retcode == 0)
					{
						type = buffer.readByte();
						this.sendNotification(NotificationConstants.COMMON_DROP_TIME,type);
					}
					else
					{
						Alert.showErrorTip(ErrorTips.instance.getCErrorTip(retcode) + "");
					}
					return true;
				}
			}
			return false;
		}
		/**
		 *去除冷却时间 
		 * @param type
		 * 
		 */		
		public function dropTime(type :int):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 1,CMD_Logic.MAIN,CMD_Logic.DROP_BUILDING_Time,0);
			sendBuf.writeByte(type);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 *比赛抽奖 
		 * @param param
		 */		
		public function getMatchAward(param:Object):void
		{
			var sendBuf :ByteArray = 
				CMD_Head.getHeadByteArrayBuff(CMD_Head.Size + 5,CMD_Pub_Match_Result.MAIN,CMD_Logic.MATCH_END_GET_AWARD,0);
			sendBuf.writeByte(param.index);
			//sendBuf.writeByte(param.matchtype);
			sendBuf.writeUnsignedInt(param.rewardid);
			sendBuf.position = 0;
			clientSocket.sendData(sendBuf,sendBuf.bytesAvailable);
		}
		/**
		 * 获取俱乐部抽奖信息
		 * @param param
		 */		
		public function getClubReward(param:Object):void
		{
			var variables:URLVariables = ProxyUtils.instance.getUrlVariables();
			variables.method = HttpRequestConst.CLUB_GET_CLUB_AWARD;
			ProxyUtils.instance.webClient(getClubRewardRes,variables,false);
		}
		/**
		 * 获取俱乐部抽奖信息   result
		 * @param data
		 * 
		 */		
		private function getClubRewardRes(data :Object):void
		{
			var str:String = String(data);
			var resultObj :Object;
			try
			{
				resultObj = JSON.decode(str)[0];
			}
			catch(e :Error)
			{
				trace("getClubRewardRes:",e);
				trace("data:",str);
				return;
			}
			if(resultObj == null)
			{
				trace("",str);
				return;
			}
			if(resultObj.retcode != 0)
			{
				return;
			}
			var rewardList :Array = resultObj.reward;
			for each(var robj :Object in rewardList)
			{
				var matchEndAwardVo :MatchEndAwardVo = new MatchEndAwardVo();
				matchEndAwardVo.rewardid = robj.rewardid;
				matchEndAwardVo.matchtype = robj.matchtype;
				this.sendNotification(NotificationConstants.MATCH_SHOW_AWARD,matchEndAwardVo);
			}
		}
	}
}